import React, { Component } from 'react';
import { ListView, Toast } from 'antd-mobile';
import { hashHistory } from 'react-router';
import './main.less';

import * as common from 'common/common.js';
import * as voteApi from 'common/api/voteapi.js';
import SeperateLine from 'common/components/SeperateLine.js';

const title_bg = {
  background: `url(${"assets/img/img_bg_01.png"})`,
  backgroundSize: "cover",
	backgroundRepeat: "no-repeat"
};

const main_bg = {
  background: `url(${"assets/img/bg.jpg"})`,
  backgroundSize: "cover",
	backgroundRepeat: "no-repeat"
};

/**
 * 主页
 * @param {voteRule} 		投票规则
 * @param {voteTime} 		投票时间
 * @param {categoryList}栏目分类
 * @param {videoList}		栏目下节目列表数据
 */
class Main extends Component{
	
	constructor(props) {
	    super(props);
	    const ds = new ListView.DataSource({
	      rowHasChanged: (row1, row2) => row1 !== row2
	    });
	    this.fetchData = [];
	    this.state = {
	    	selectedVideo1: common.cacheGet("selectedVideo1") ? common.cacheGet("selectedVideo1") : [],
	    	selectedVideo2: common.cacheGet("selectedVideo2") ? common.cacheGet("selectedVideo2") : [],
	    	selectedVideo3: common.cacheGet("selectedVideo3") ? common.cacheGet("selectedVideo3") : [],
	    	hasMore: true,
    	 	pageNo: 0,
    	 	pageTotal: 100,
      	ds: ds,
      	isLoading: true,
      	height: document.documentElement.clientHeight * 3 / 4,
	    	selectedIndex: 0,
	    	voteRule: "用户可在湖北省纪委监委网站客户端、湖北省纪委监委网站、长江云客户端进行投票。没人每天可投票1次,每个类别需选投9个作品,三个类别的作品共计27票。",
	    	voteTime: "2018年8月1日 —— 8月10日",
	    	categoryList: [
	    		"微视频", "微动漫", "电视广告"
	    	],
	    	videoList: []
	    }
	}
	
	//是否在数组中
	isInArray = (arr,value) => {
    for(var i = 0; i < arr.length; i++){
        if(value === arr[i]){
            return true;
        }
    }
    return false;
	}
	
	//数组位置
	indexInArray = (arr,value) => {
    for(var i = 0; i < arr.length; i++){
        if(value === arr[i]){
            return i;
        }
    }
    return -1;
	}
	
	//切换tab
	changeTab = (index) => {
		const height = document.documentElement.clientHeight;
		this.fetchData = [];
		this.setState({
	    ds: this.state.ds.cloneWithRows(this.fetchData),
	    isLoading: false,
	    height: height
		});
			
		setTimeout(() => {
      	voteApi.videoList({
					page: 0,
					videoType: "0"
		  	}).then(result => {
		  		if(result.resultCode == "0"){
		  			this.fetchData = [ ...this.fetchData, ...result.resultData.videoList];
						this.setState({
			        ds: this.state.ds.cloneWithRows(this.fetchData),
			        isLoading: false,
			        height: height,
			        selectedIndex: index
		      	});
		  		}
		  	})
    }, 500);
	}
	
	//查看详情
	detail = (item) => {
		hashHistory.push("/detail/"+item.videoId)
	}
	
	//选择
	select = (item) => {
		const { selectedIndex } = this.state;
		if(selectedIndex == 0){
			var array = this.state.selectedVideo1;
			if(!this.isInArray(array, item.videoId)){
				if(array.length >= 9){
					Toast.info("最多选择9个", 1)
					return;
				}
				array.push(item.videoId);
			}else{
				array.splice(this.indexInArray(array, item.videoId), 1)
			}
			common.cacheSet("selectedVideo1", array);
			this.setState({
				selectedVideo1: array
			})
		}else if(selectedIndex == 1){
			var array = this.state.selectedVideo2;
			if(!this.isInArray(array, item.videoId)){
				if(array.length >= 9){
					Toast.info("最多选择9个", 1)
					return;
				}
				array.push(item.videoId);
			}else{
				array.splice(this.indexInArray(array, item.videoId), 1)
			}
			this.setState({
				selectedVideo2: array
			})
			common.cacheSet("selectedVideo2", array);
		}else if(selectedIndex == 2){
			var array = this.state.selectedVideo3;
			if(!this.isInArray(array, item.videoId)){
				if(array.length >= 9){
					Toast.info("最多选择9个", 1)
					return;
				}
				array.push(item.videoId);
			}else{
				array.splice(this.indexInArray(array, item.videoId), 1)
			}
			this.setState({
				selectedVideo3: array
			})
			common.cacheSet("selectedVideo3", array);
		}
	}
	
	renderRow = (item,rowId) => {
		const { selectedIndex, selectedVideo1, selectedVideo2, selectedVideo3 } = this.state;
		var name = "选择";
		var nameSelected = "btn";
//		var array = [];
//		if(selectedIndex == 0){
//			array = this.state.selectedVideo1;
//		}else if(selectedIndex == 1){
//			array = this.state.selectedVideo2;
//		}else if(selectedIndex == 2){
//			array = this.state.selectedVideo3;
//			
//		}
//		if(this.isInArray(array, item.videoId)){
//			name = "已选";
//			nameSelected = "btn btn_selected";
//		}
    return (
      <div key={item.videoId} className="vote_list_item_box">
				<div className="vote_list_item">
					<img src={item.videoImg} onClick={() => this.detail(item)}/>
					<div className="info">
						<span>作品名: {item.videoName}</span>
						<span>票数: {item.voteNum}</span>
					</div>
					<div className={nameSelected} onClick={() => this.select(item)}>
						<span>{name}</span>
					</div>
				</div>
			</div>
    )
	}
	
	componentDidMount() {
		const height = document.documentElement.clientHeight;
		setTimeout(() => {
      	voteApi.videoList({
					page: 0,
					videoType: "0"
		  	}).then(result => {
		  		if(result.resultCode == "0"){
		  			this.fetchData = [ ...this.fetchData, ...result.resultData.videoList];
						this.setState({
			        ds: this.state.ds.cloneWithRows(this.fetchData),
			        isLoading: false,
			        height: height
		      	});
		  		}
		  	})
    }, 500);
	}
	
	onEndReached = (event) => {
		const height = document.documentElement.clientHeight;
		if (this.state.isLoading && !this.state.hasMore) {
      	return;
    }
    this.setState({ 
      	isLoading: true, 
      	pageNo: this.state.pageNo + 1
    });
		setTimeout(() => {
      	voteApi.videoList({
					page: this.state.pageNo,
					videoType: "0"
		  	}).then(result => {
		  		if(result.resultCode == "0"){
		  			if(result.resultData.videoList){
		  				this.fetchData = [ ...this.fetchData, ...result.resultData.videoList];
							this.setState({
				        ds: this.state.ds.cloneWithRows(this.fetchData),
				        isLoading: false,
				        height: height
			      	});
		  			}else{
		  				this.setState({
				    		hasMore: false
				    	})
				    	return;
		  			}
		  		}
		  	})
    }, 500);
	}
	
	//投票
	vote = () => {
		var voteTime = common.storeGet("vote");
		if(voteTime){
			var todayDate = new Date().getDate();
			var voteDate = new Date(voteTime).getDate();
			if(todayDate != voteDate){
				Toast.info(this.state.selectedVideo1, 1)
				Toast.info(this.state.selectedVideo2, 1)
				Toast.info(this.state.selectedVideo3, 1)
				voteApi.verificationCode().then(result => {
		  		if(result.resultCode == "0"){
		  			voteApi.voteVideo({
		  				code: result.resultData.code,
		  				token: result.resultData.token,
		  				videoId: '001'
		  			}).then(result => {
				  		if(result.resultCode == "0"){
				  			Toast.info("投票成功!")
				  			common.storeSet("vote", new Date());
				  		}
				  	})
		  		}
		  	})
			}else{
				Toast.info("您今日已投过票!")
			}
		}else{
			Toast.info(this.state.selectedVideo1, 1)
			Toast.info(this.state.selectedVideo2, 1)
			Toast.info(this.state.selectedVideo3, 1)
			voteApi.verificationCode().then(result => {
	  		if(result.resultCode == "0"){
	  			voteApi.voteVideo({
	  				code: result.resultData.code,
	  				token: result.resultData.token,
	  				videoId: '001'
	  			}).then(result => {
			  		if(result.resultCode == "0"){
			  			Toast.info("投票成功!")
			  			common.storeSet("vote", new Date());
			  		}
			  	})
	  		}
	  	})
		}
	}
	
	render(){
		const { selectedVideo1, selectedVideo2, selectedVideo3, voteRule, voteTime, categoryList, videoList } = this.state;
		
		return(
			<div className="main" style={main_bg}>
				<ListView
	        style={{
	          height: this.state.height,
	          overflow: 'auto'
	        }}
	        ref={el => this.lv = el}
	        dataSource={this.state.ds}
	        renderRow={this.renderRow}
	        renderHeader={() => (
	        	<div>
	        		{/* 头部介绍 */}
							<div className="title" style={title_bg}>
								<span className="title_01">廉风润荆楚</span>
								<span className="title_02">2018年廉政公益广告作品</span>
								<span className="title_03">网络投票</span>
							</div>
							
							{/* 投票规则 */}
							<div className="vote_rule_title">
								<span style={{backgroundImage: `url(${"assets/img/title_bg1.png"})`,backgroundRepeat: "no-repeat",backgroundSize: "2.04rem 0.7rem"}}>投票规则</span>
							</div>
							<div className="vote_rule_box">
								<div className="vote_rule">
									<div className="vote_rule_01">
										<span style={{fontSize:"0.28rem"}}>
											<em style={{fontSize:"0.28rem"}}>投票规则:&nbsp;&nbsp;</em>{voteRule}
										</span>
									</div>
									<div className="vote_rule_02">
										<span style={{fontSize:"0.28rem"}}>
											<em style={{fontSize:"0.28rem"}}>投票时间:&nbsp;&nbsp;</em>{voteTime}
										</span>
									</div>
								</div>
							</div>
							
							{/* 列表区域 */}
							<div className="vote_list_box">
								<div className="vote_list_title">
									{
										categoryList.map((item, index) => {
											if(this.state.selectedIndex == index){
												return(
													<span key={index} style={{backgroundImage: `url(${"assets/img/title_bg1.png"})`,backgroundRepeat: "no-repeat",backgroundSize: "2.04rem 0.7rem"}} onClick={() => this.changeTab(index)}>{item}</span>
												)
											}else{
												return(
													<span key={index} style={{backgroundImage: `url(${"assets/img/title_bg2.jpg"})`,backgroundRepeat: "no-repeat",backgroundSize: "2.04rem 0.7rem"}} onClick={() => this.changeTab(index)}>{item}</span>
												)
											}
										})
									}
								</div>
							</div>
							<div style={{height: '0.3rem'}}></div>
	        	</div>
	        )}
	        renderFooter={() => (
	          <div style={{ padding: 30, textAlign: 'center', fontSize: '0.28rem' }}>
	          	{
	          		this.state.hasMore 
	          		?
	          			this.state.isLoading
	          			?
	          			'加载中...' 
	          			: 
	          			'上拉加载'
	          		:
	          		'加载完毕'
	          	}
	          </div>
	        )}
	        renderBodyComponent={() => (
	        	<div style={{padding: '0 0.25rem'}}>{this.children}</div>
	        )}
	        pageSize={12}
	        scrollRenderAheadDistance={500}
	        onEndReached={this.onEndReached}
	        onEndReachedThreshold={10}
      	/>
				
				{/* 隔离高度 */}
				<div style={{clear: 'both',height: "0.5rem"}}></div>
				
				{/* 底部菜单 */}
				<div className="vote_bottom">
					<div className="left">
						已选
					</div>
					<div className="content">
						<div className="top">
							<span><em>{selectedVideo1.length}个</em>微视频</span>
							<span><em>{selectedVideo2.length}个</em>微动漫</span>
						</div>
						<div className="bottom">
							<span><em>{selectedVideo3.length}个</em>电视广告</span>
						</div>
					</div>
					<div className="right" onClick={this.vote.bind(this)}>
						投票
					</div>
				</div>
			</div>
		)
	}
}

export default Main;